home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Python / errors.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-08-03  |  9.3 KB  |  458 lines

  1. /* Error handling */
  2.  
  3. #include "Python.h"
  4.  
  5. #ifdef SYMANTEC__CFM68K__
  6. #pragma lib_export on
  7. #endif
  8.  
  9. #ifdef macintosh
  10. extern char *PyMac_StrError Py_PROTO((int));
  11. #undef strerror
  12. #define strerror PyMac_StrError
  13. #endif /* macintosh */
  14.  
  15. #ifndef __STDC__
  16. #ifndef MS_WINDOWS
  17. extern char *strerror Py_PROTO((int));
  18. #endif
  19. #endif
  20.  
  21. #ifdef MS_WIN32
  22. #include "windows.h"
  23. #include "winbase.h"
  24. #endif
  25.  
  26. void
  27. PyErr_Restore(type, value, traceback)
  28.     PyObject *type;
  29.     PyObject *value;
  30.     PyObject *traceback;
  31. {
  32.     PyThreadState *tstate = PyThreadState_GET();
  33.     PyObject *oldtype, *oldvalue, *oldtraceback;
  34.  
  35.     if (traceback != NULL && !PyTraceBack_Check(traceback)) {
  36.         /* XXX Should never happen -- fatal error instead? */
  37.         Py_DECREF(traceback);
  38.         traceback = NULL;
  39.     }
  40.  
  41.     /* Save these in locals to safeguard against recursive
  42.        invocation through Py_XDECREF */
  43.     oldtype = tstate->curexc_type;
  44.     oldvalue = tstate->curexc_value;
  45.     oldtraceback = tstate->curexc_traceback;
  46.  
  47.     tstate->curexc_type = type;
  48.     tstate->curexc_value = value;
  49.     tstate->curexc_traceback = traceback;
  50.  
  51.     Py_XDECREF(oldtype);
  52.     Py_XDECREF(oldvalue);
  53.     Py_XDECREF(oldtraceback);
  54. }
  55.  
  56. void
  57. PyErr_SetObject(exception, value)
  58.     PyObject *exception;
  59.     PyObject *value;
  60. {
  61.     Py_XINCREF(exception);
  62.     Py_XINCREF(value);
  63.     PyErr_Restore(exception, value, (PyObject *)NULL);
  64. }
  65.  
  66. void
  67. PyErr_SetNone(exception)
  68.     PyObject *exception;
  69. {
  70.     PyErr_SetObject(exception, (PyObject *)NULL);
  71. }
  72.  
  73. void
  74. PyErr_SetString(exception, string)
  75.     PyObject *exception;
  76.     const char *string;
  77. {
  78.     PyObject *value = PyString_FromString(string);
  79.     PyErr_SetObject(exception, value);
  80.     Py_XDECREF(value);
  81. }
  82.  
  83.  
  84. PyObject *
  85. PyErr_Occurred()
  86. {
  87.     PyThreadState *tstate = PyThreadState_Get();
  88.  
  89.     return tstate->curexc_type;
  90. }
  91.  
  92.  
  93. int
  94. PyErr_GivenExceptionMatches(err, exc)
  95.      PyObject *err, *exc;
  96. {
  97.     if (err == NULL || exc == NULL) {
  98.         /* maybe caused by "import exceptions" that failed early on */
  99.         return 0;
  100.     }
  101.     if (PyTuple_Check(exc)) {
  102.         int i, n;
  103.         n = PyTuple_Size(exc);
  104.         for (i = 0; i < n; i++) {
  105.             /* Test recursively */
  106.              if (PyErr_GivenExceptionMatches(
  107.                  err, PyTuple_GET_ITEM(exc, i)))
  108.              {
  109.                  return 1;
  110.              }
  111.         }
  112.         return 0;
  113.     }
  114.     /* err might be an instance, so check its class. */
  115.     if (PyInstance_Check(err))
  116.         err = (PyObject*)((PyInstanceObject*)err)->in_class;
  117.  
  118.     if (PyClass_Check(err) && PyClass_Check(exc))
  119.         return PyClass_IsSubclass(err, exc);
  120.  
  121.     return err == exc;
  122. }
  123.  
  124.  
  125. int
  126. PyErr_ExceptionMatches(exc)
  127.      PyObject *exc;
  128. {
  129.     return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
  130. }
  131.  
  132.  
  133. /* Used in many places to normalize a raised exception, including in
  134.    eval_code2(), do_raise(), and PyErr_Print()
  135. */
  136. void
  137. PyErr_NormalizeException(exc, val, tb)
  138.      PyObject **exc;
  139.      PyObject **val;
  140.      PyObject **tb;
  141. {
  142.     PyObject *type = *exc;
  143.     PyObject *value = *val;
  144.     PyObject *inclass = NULL;
  145.  
  146.     /* If PyErr_SetNone() was used, the value will have been actually
  147.        set to NULL.
  148.     */
  149.     if (!value) {
  150.         value = Py_None;
  151.         Py_INCREF(value);
  152.     }
  153.  
  154.     if (PyInstance_Check(value))
  155.         inclass = (PyObject*)((PyInstanceObject*)value)->in_class;
  156.  
  157.     /* Normalize the exception so that if the type is a class, the
  158.        value will be an instance.
  159.     */
  160.     if (PyClass_Check(type)) {
  161.         /* if the value was not an instance, or is not an instance
  162.            whose class is (or is derived from) type, then use the
  163.            value as an argument to instantiation of the type
  164.            class.
  165.         */
  166.         if (!inclass || !PyClass_IsSubclass(inclass, type)) {
  167.             PyObject *args, *res;
  168.  
  169.             if (value == Py_None)
  170.                 args = Py_BuildValue("()");
  171.             else if (PyTuple_Check(value)) {
  172.                 Py_INCREF(value);
  173.                 args = value;
  174.             }
  175.             else
  176.                 args = Py_BuildValue("(O)", value);
  177.  
  178.             if (args == NULL)
  179.                 goto finally;
  180.             res = PyEval_CallObject(type, args);
  181.             Py_DECREF(args);
  182.             if (res == NULL)
  183.                 goto finally;
  184.             Py_DECREF(value);
  185.             value = res;
  186.         }
  187.         /* if the class of the instance doesn't exactly match the
  188.            class of the type, believe the instance
  189.         */
  190.         else if (inclass != type) {
  191.              Py_DECREF(type);
  192.             type = inclass;
  193.             Py_INCREF(type);
  194.         }
  195.     }
  196.     *exc = type;
  197.     *val = value;
  198.     return;
  199. finally:
  200.     Py_DECREF(type);
  201.     Py_DECREF(value);
  202.     Py_XDECREF(*tb);
  203.     PyErr_Fetch(exc, val, tb);
  204.     /* normalize recursively */
  205.     PyErr_NormalizeException(exc, val, tb);
  206. }
  207.  
  208.  
  209. void
  210. PyErr_Fetch(p_type, p_value, p_traceback)
  211.     PyObject **p_type;
  212.     PyObject **p_value;
  213.     PyObject **p_traceback;
  214. {
  215.     PyThreadState *tstate = PyThreadState_Get();
  216.  
  217.     *p_type = tstate->curexc_type;
  218.     *p_value = tstate->curexc_value;
  219.     *p_traceback = tstate->curexc_traceback;
  220.  
  221.     tstate->curexc_type = NULL;
  222.     tstate->curexc_value = NULL;
  223.     tstate->curexc_traceback = NULL;
  224. }
  225.  
  226. void
  227. PyErr_Clear()
  228. {
  229.     PyErr_Restore(NULL, NULL, NULL);
  230. }
  231.  
  232. /* Convenience functions to set a type error exception and return 0 */
  233.  
  234. int
  235. PyErr_BadArgument()
  236. {
  237.     PyErr_SetString(PyExc_TypeError,
  238.             "illegal argument type for built-in operation");
  239.     return 0;
  240. }
  241.  
  242. PyObject *
  243. PyErr_NoMemory()
  244. {
  245.     /* raise the pre-allocated instance if it still exists */
  246.     if (PyExc_MemoryErrorInst)
  247.         PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
  248.     else
  249.         /* this will probably fail since there's no memory and hee,
  250.            hee, we have to instantiate this class
  251.         */
  252.         PyErr_SetNone(PyExc_MemoryError);
  253.  
  254.     return NULL;
  255. }
  256.  
  257. PyObject *
  258. PyErr_SetFromErrnoWithFilename(exc, filename)
  259.     PyObject *exc;
  260.     char *filename;
  261. {
  262.     PyObject *v;
  263.     char *s;
  264.     int i = errno;
  265. #ifdef MS_WIN32
  266.     char *s_buf = NULL;
  267. #endif
  268. #ifdef EINTR
  269.     if (i == EINTR && PyErr_CheckSignals())
  270.         return NULL;
  271. #endif
  272.     if (i == 0)
  273.         s = "Error"; /* Sometimes errno didn't get set */
  274.     else
  275. #ifndef MS_WIN32
  276.         s = strerror(i);
  277. #else
  278.     {
  279.         /* Note that the Win32 errors do not lineup with the
  280.            errno error.  So if the error is in the MSVC error
  281.            table, we use it, otherwise we assume it really _is_ 
  282.            a Win32 error code
  283.         */
  284.         if (i > 0 && i < _sys_nerr) {
  285.             s = _sys_errlist[i];
  286.         }
  287.         else {
  288.             int len = FormatMessage(
  289.                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
  290.                 FORMAT_MESSAGE_FROM_SYSTEM |
  291.                 FORMAT_MESSAGE_IGNORE_INSERTS,
  292.                 NULL,    /* no message source */
  293.                 i,
  294.                 MAKELANGID(LANG_NEUTRAL,
  295.                        SUBLANG_DEFAULT),
  296.                            /* Default language */
  297.                 (LPTSTR) &s_buf,
  298.                 0,    /* size not used */
  299.                 NULL);    /* no args */
  300.             s = s_buf;
  301.             /* remove trailing cr/lf and dots */
  302.             while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
  303.                 s[--len] = '\0';
  304.         }
  305.     }
  306. #endif
  307.     if (filename != NULL)
  308.         v = Py_BuildValue("(iss)", i, s, filename);
  309.     else
  310.         v = Py_BuildValue("(is)", i, s);
  311.     if (v != NULL) {
  312.         PyErr_SetObject(exc, v);
  313.         Py_DECREF(v);
  314.     }
  315. #ifdef MS_WIN32
  316.     LocalFree(s_buf);
  317. #endif
  318.     return NULL;
  319. }
  320.  
  321.  
  322. PyObject *
  323. PyErr_SetFromErrno(exc)
  324.     PyObject *exc;
  325. {
  326.     return PyErr_SetFromErrnoWithFilename(exc, NULL);
  327. }
  328.  
  329. #ifdef MS_WINDOWS 
  330. /* Windows specific error code handling */
  331. PyObject *PyErr_SetFromWindowsErrWithFilename(
  332.     int ierr, 
  333.     const char *filename)
  334. {
  335.     int len;
  336.     char *s;
  337.     PyObject *v;
  338.     DWORD err = (DWORD)ierr;
  339.     if (err==0) err = GetLastError();
  340.     len = FormatMessage(
  341.         /* Error API error */
  342.         FORMAT_MESSAGE_ALLOCATE_BUFFER |
  343.         FORMAT_MESSAGE_FROM_SYSTEM |
  344.         FORMAT_MESSAGE_IGNORE_INSERTS,
  345.         NULL,    /* no message source */
  346.         err,
  347.         MAKELANGID(LANG_NEUTRAL,
  348.         SUBLANG_DEFAULT), /* Default language */
  349.         (LPTSTR) &s,
  350.         0,    /* size not used */
  351.         NULL);    /* no args */
  352.     /* remove trailing cr/lf and dots */
  353.     while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
  354.         s[--len] = '\0';
  355.     if (filename != NULL)
  356.         v = Py_BuildValue("(iss)", err, s, filename);
  357.     else
  358.         v = Py_BuildValue("(is)", err, s);
  359.     if (v != NULL) {
  360.         PyErr_SetObject(PyExc_WindowsError, v);
  361.         Py_DECREF(v);
  362.     }
  363.     LocalFree(s);
  364.     return NULL;
  365. }
  366.  
  367. PyObject *PyErr_SetFromWindowsErr(int ierr)
  368. {
  369.     return PyErr_SetFromWindowsErrWithFilename(ierr, NULL);
  370.  
  371. }
  372. #endif /* MS_WINDOWS */
  373.  
  374. void
  375. PyErr_BadInternalCall()
  376. {
  377.     PyErr_SetString(PyExc_SystemError,
  378.             "bad argument to internal function");
  379. }
  380.  
  381.  
  382. #ifdef HAVE_STDARG_PROTOTYPES
  383. PyObject *
  384. PyErr_Format(PyObject *exception, const char *format, ...)
  385. #else
  386. PyObject *
  387. PyErr_Format(exception, format, va_alist)
  388.     PyObject *exception;
  389.     const char *format;
  390.     va_dcl
  391. #endif
  392. {
  393.     va_list vargs;
  394.     char buffer[500]; /* Caller is responsible for limiting the format */
  395.  
  396. #ifdef HAVE_STDARG_PROTOTYPES
  397.     va_start(vargs, format);
  398. #else
  399.     va_start(vargs);
  400. #endif
  401.  
  402.     vsprintf(buffer, format, vargs);
  403.     PyErr_SetString(exception, buffer);
  404.     return NULL;
  405. }
  406.  
  407.  
  408. PyObject *
  409. PyErr_NewException(name, base, dict)
  410.     char *name; /* modulename.classname */
  411.     PyObject *base;
  412.     PyObject *dict;
  413. {
  414.     char *dot;
  415.     PyObject *modulename = NULL;
  416.     PyObject *classname = NULL;
  417.     PyObject *mydict = NULL;
  418.     PyObject *bases = NULL;
  419.     PyObject *result = NULL;
  420.     dot = strrchr(name, '.');
  421.     if (dot == NULL) {
  422.         PyErr_SetString(PyExc_SystemError,
  423.             "PyErr_NewException: name must be module.class");
  424.         return NULL;
  425.     }
  426.     if (base == NULL)
  427.         base = PyExc_Exception;
  428.     if (!PyClass_Check(base)) {
  429.         /* Must be using string-based standard exceptions (-X) */
  430.         return PyString_FromString(name);
  431.     }
  432.     if (dict == NULL) {
  433.         dict = mydict = PyDict_New();
  434.         if (dict == NULL)
  435.             goto failure;
  436.     }
  437.     if (PyDict_GetItemString(dict, "__module__") == NULL) {
  438.         modulename = PyString_FromStringAndSize(name, (int)(dot-name));
  439.         if (modulename == NULL)
  440.             goto failure;
  441.         if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
  442.             goto failure;
  443.     }
  444.     classname = PyString_FromString(dot+1);
  445.     if (classname == NULL)
  446.         goto failure;
  447.     bases = Py_BuildValue("(O)", base);
  448.     if (bases == NULL)
  449.         goto failure;
  450.     result = PyClass_New(bases, dict, classname);
  451.   failure:
  452.     Py_XDECREF(bases);
  453.     Py_XDECREF(mydict);
  454.     Py_XDECREF(classname);
  455.     Py_XDECREF(modulename);
  456.     return result;
  457. }
  458.